<template>
  <div class="app-container inden-manage sticky-box">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <template #warrantyDateArr>
          <DatePickerRange
            v-model="queryParams.warrantyDateArr"
            range-separator="-"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            :clearable="false"
            @change="
              () => {
                queryParams.warrantyStartDate = queryParams?.warrantyDateArr[0]
                queryParams.warrantyEndDate = queryParams?.warrantyDateArr[1]
              }
            "
            startPlaceholder="保修期开始时间"
            endPlaceholder="保修期结束时间"
          />
        </template>
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
        </template>
      </avue-form>

      <el-row :gutter="10" class="my-4">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleOpen"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="EditPen"
            plain
            @click="handleUpdate"
            :disabled="disUpdate"
            >编辑</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Delete"
            plain
            @click="handleDelete"
            :disabled="disDelete"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Share"
            plain
            @click="handleRenew"
            :disabled="disUpdate"
            >续费</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Upload"
            plain
            @click="
              () => {
                uploadDia.open = true
              }
            "
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="Download" plain @click="exportDetail"
            >导出</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Aim"
            @click="apportionLog"
            :disabled="disDelete"
            >分配</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Histogram"
            plain
            @click="handleStatistics"
            >统计</el-button
          >
        </el-col>
        <right-toolbar @queryTable="getList" v-model:showSearch="showSearch">
          <el-tooltip
            class="item"
            effect="dark"
            :content="'自定义列表'"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </right-toolbar>
      </el-row>

      <el-table
        class="sticky-table"
        v-loading="loading"
        :data="tableList"
        row-key="id"
        stripe
        border
        :scrollbar-always-on="true"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column
          type="selection"
          width="40"
          align="center"
          fixed="left"
        /> -->
        <el-table-column
          v-for="(item, index) in tableCol.filter(item => item.show)"
          :key="index"
          v-bind="item"
        >
          <template #default="scope">
            <div v-if="item.tooltip">
              <el-tooltip
                :disabled="!scope.row.invoiceMsg"
                effect="dark"
                :content="item.tooltip(scope.row)"
                placement="top"
              >
                {{ item.tooltipVal(scope.row) }}
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="120"
          fixed="right"
          class-name="small-padding"
        >
          <template #default="scope">
            <el-dropdown type="primary" class="align-middle">
              <el-button link type="primary"
                >更多 <el-icon class="el-icon--right"> <arrow-down /> </el-icon
              ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleAccess(scope.row)"
                    >跟进</el-dropdown-item
                  >
                  <el-dropdown-item @click="handleAccessDia(scope.row)"
                    >跟进记录</el-dropdown-item
                  >
                  <el-dropdown-item @click="uploadContract(scope.row)"
                    >上传合同</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 自定义订单列表弹窗 -->
      <DiaFixTable
        v-model="diaTable.open"
        :dialogParam="diaTable"
        @ok="diaTableFn"
      />

      <!-- 导入弹窗 -->
      <el-dialog
        :title="uploadDia.title"
        v-model="uploadDia.open"
        width="400px"
        append-to-body
        @close="closeUpload"
        :close-on-click-modal="false"
      >
        <el-upload
          v-loading="uploadLoading"
          action="#"
          :before-upload="rawFile => beforeAvatarUpload(rawFile, 'type01')"
          :http-request="params => requestFile(params, 'type01')"
          :accept="uploadType['type01'].toString()"
          :show-file-list="false"
          drag
        >
          <el-icon class="el-icon--upload">
            <upload-filled />
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div>
              <div class="el-upload__tip text-center">
                <span class="text-red"
                  >仅允许导入{{ uploadType['type01'].toString() }}</span
                >
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; vertical-align: baseline"
                  @click="downUrl"
                  >下载模板
                </el-link>
              </div>
              <div v-if="uploadDia.message" style="white-space: pre-line">
                导入结果：{{ uploadDia.message }}
              </div>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
            <el-button @click="closeUpload">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 跟进弹窗 -->
    <AccessForm
      :dialogParam="accessParam"
      @close="
        () => {
          accessParam.isVisible = false
        }
      "
    ></AccessForm>

    <!-- 跟进记录 -->
    <el-dialog
      :title="AccessDia.title"
      v-model="AccessDia.open"
      :width="AccessDia.width"
      append-to-body
      @close="closeAccessDia"
      :close-on-click-modal="false"
    >
      <AccessList :tableParam="AccessDia.tableParam" />
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
          <el-button @click="closeAccessDia">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 统计 -->
    <el-dialog
      :title="statisticsDia.title"
      v-model="statisticsDia.open"
      :width="statisticsDia.width"
      append-to-body
      @close="closeStatisticsDia"
      :close-on-click-modal="false"
    >
      <div>
        <el-row :gutter="20">
          <!--供应商列表-->
          <el-col :span="24">
            <el-form
              :model="queryParamsStatistics"
              ref="queryRef"
              :inline="true"
              label-width="0"
              @submit.prevent
              @keyup.enter="getListStatistics"
            >
              <div class="flex">
                <div class="w-6/24">
                  <el-form-item prop="city">
                    <el-select
                      clearable
                      class="w-full"
                      v-model="queryParamsStatistics.city"
                      placeholder="请选择服务单位"
                      @change="getListStatistics"
                    >
                      <el-option
                        v-for="item in taxTreeData[0]?.children"
                        :key="item.id"
                        :label="item.label"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="w-6/24">
                  <el-form-item prop="status">
                    <el-select
                      clearable
                      class="w-full"
                      v-model="queryParamsStatistics.status"
                      placeholder="请选择状态"
                      @change="getListStatistics"
                    >
                      <el-option
                        v-for="item in enable_status"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="w-12/24">注:选择单位，按网点类型统计</div>
              </div>
            </el-form>
            <!-- <div>
              <span>数量：{{ dataListStatistics.num }}</span>
            </div> -->
            <el-table
              v-loading="loadingStatistics"
              :data="dataListStatistics"
              border
              stripe
              @row-dblclick="handleDbClick"
            >
              <el-table-column
                type="index"
                width="60"
                label="序号"
                align="center"
                fixed="left"
              />
              <el-table-column prop="name" label="单位/网点"> </el-table-column>
              <el-table-column prop="taxTerminalNum" label="税务终端">
              </el-table-column>
              <el-table-column
                prop="exitAndEntryTerminalNum"
                label="出入境终端"
              >
              </el-table-column>
              <el-table-column
                prop="industrialAndCommercialTerminalNum"
                label="工商终端"
              >
              </el-table-column>
              <el-table-column
                prop="residencePermitDeviceNum"
                label="居住证设备"
              >
              </el-table-column>
              <el-table-column prop="subtotal" label="小计"> </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
          <el-button @click="closeStatisticsDia">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 关联订单 -->
    <RelatedOrder
      :relatedParams="orderParams"
      @closeDialog="ordCloseDialog"
      @relatedOver="ordRelatedOver"
    />

    <!-- 关联合同 -->
    <SelectContract
      :dialogParam="diaParam"
      @ok="saveFn"
      @close="diaParam.open = false"
    />

    <!-- 表单弹窗 -->
    <el-dialog
      :title="formDialog.title"
      v-model="formDialog.open"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="市局" prop="city">
              <el-select
                class="w-full"
                v-model="formData.city"
                placeholder="请选择市局"
                @change="changeTax"
              >
                <el-option
                  v-for="item in taxTreeData[0]?.children"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区局" prop="district">
              <el-select
                class="w-full"
                v-model="formData.district"
                placeholder="请选择市局"
              >
                <el-option
                  v-for="item in taxDistrictBureau"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceType">
              <el-tree-select
                class="w-full"
                v-model="formData.deviceType"
                placeholder="请选择设备型号"
                default-expand-all
                :checkStrictly="false"
                filterable
                :data="terminalDeviceTree"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名称" prop="customerName">
              <el-input
                v-model="formData.customerName"
                placeholder="请输入单位名称"
              >
                <template #append>
                  <el-button type="primary" @click="activeOrdDialog">
                    订单
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网点类型" prop="networkType">
              <el-select
                class="w-full"
                v-model="formData.networkType"
                placeholder="请选择网点类型"
              >
                <el-option
                  v-for="item in terminal_network_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="序列号" prop="serialNumber">
              <el-input
                v-model="formData.serialNumber"
                placeholder="请输入序列号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运维人员" prop="operations">
              <el-input
                v-model="formData.operations"
                placeholder="请输入运维人员"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="formData.contact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="telephone">
              <el-input v-model="formData.telephone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                class="w-full"
                v-model="formData.status"
                placeholder="请选择状态"
              >
                <el-option
                  v-for="item in enable_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买时间" prop="purchaseDate">
              <el-date-picker
                style="width: 100%"
                v-model="formData.purchaseDate"
                type="date"
                placeholder="请选择购买时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保修期" prop="warrantyDate">
              <el-date-picker
                style="width: 100%"
                v-model="formData.warrantyDate"
                type="date"
                placeholder="请选择保修期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否延保" prop="isWarranty">
              <el-select
                class="w-full"
                v-model="formData.isWarranty"
                placeholder="请选择是否延保"
              >
                <el-option
                  v-for="item in yes_or_no"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否已续费" prop="isRenewal">
              <el-select
                class="w-full"
                v-model="formData.isRenewal"
                placeholder="请选择是否已续费"
              >
                <el-option
                  v-for="item in yes_or_no"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </span></template
      >
    </el-dialog>
  </div>
</template>
<script setup name="TerminalManage">
import { reactive, toRefs, ref, toRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  listTerminal,
  saveTerminal,
  renewTerminal,
  delTerminal,
  getTerminal,
  statisticsTerminal,
  importTerminal
} from '@/api/terminal/index'
import { supervisionContract } from '@/api/supervision/contract'
import { initTable } from '@/utils/commo'
import { selectDictLabel } from '@/utils/ruoyi'
import {
  companyOption //所属公司
} from '@/hooks/dict/order'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import AccessForm from './modules/accessForm'
import AccessList from './modules/accessList'
import { downLoadByUrl } from '@/utils/myDownload'
// 列表配置
const INITTABLE = [
  // {
  //   show: true,
  //   type: 'index',
  //   width: '40',
  //   label: '序号',
  //   align: 'center',
  //   fixed: 'left'
  // },
  {
    show: true,
    label: '选择',
    type: 'selection',
    width: '40',
    align: 'center',
    fixed: 'left'
  },
  {
    show: true,
    prop: 'cityName',
    label: '市局',
    align: 'center',
    width: 160,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'networkType',
    label: '网点类型',
    align: 'center',
    minWidth: 160,
    showOverflowTooltip: false,
    formatter: row => {
      return selectDictLabel(terminal_network_type.value, row.networkType)
    }
  },
  {
    show: true,
    prop: 'deviceType',
    label: '设备型号',
    align: 'center',
    minWidth: 160,
    showOverflowTooltip: false,
    formatter: row => {
      return selectDictLabel(terminal_device_type.value, row.deviceType)
    }
  },
  // {
  //   show: true,
  //   prop: 'site',
  //   label: '设备型号',
  //   align: 'center',
  //   width: 130,
  //   showOverflowTooltip: true,
  //   formatter: row => {
  //     return selectDictLabel(terminal_device_type.value, row.deviceType)
  //   }
  // },
  {
    show: true,
    prop: 'serialNumber',
    label: '序列号',
    align: 'center',
    width: 130,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'status',
    label: '状态',
    align: 'center',
    width: 100,
    showOverflowTooltip: true,
    formatter: row => {
      return selectDictLabel(enable_status.value, row.status)
    }
  },
  {
    show: true,
    prop: 'operations',
    label: '运维人员',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'address',
    label: '地址',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'contact',
    label: '联系人',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'telephone',
    label: '电话',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'warrantyDate',
    label: '保修期',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
    // formatter: row => {
    //   return parseTime(row.createTime, '{y}-{m}-{d}')
    // }
  },
  {
    show: true,
    prop: 'purchaseDate',
    label: '购买日',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'isRenewal',
    label: '是否已续费',
    align: 'center',
    width: 180,
    showOverflowTooltip: true,
    formatter: row => {
      return selectDictLabel(yes_or_no.value, row.isRenewal)
    }
  },
  {
    show: true,
    prop: 'contractInfo',
    label: '合同',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'remark',
    label: '备注',
    align: 'center',
    width: 180,
    showOverflowTooltip: true
  }
]

const commonStore = useCommonStore()

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const {
  terminal_device_type,
  terminal_network_type,
  enable_status,
  yes_or_no
} = proxy.useDict(
  'terminal_device_type', //终端设备类型
  'terminal_network_type', //终端网点类型
  'enable_status', //是否启用
  'yes_or_no' //是否
)
// 终端设备类型树
const terminalDeviceTree = ref([])
// 税务局下拉树
const taxTreeData = ref([])
// 税务区局下拉树
const taxDistrictBureau = ref([])

watchEffect(() => {
  let tree = proxy.handleTree(
    proxy.deepClone(terminal_device_type.value),
    'value'
  )
  terminalDeviceTree.value = tree
})

const userOption = ref({ userId: [] })
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orgId: userStore.userInfo.orgId == 484 ? '' : userStore.userInfo.orgId
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 7,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'orgId',
        span: 3,
        placeholder: '区域公司',
        type: 'tree',
        defaultExpandAll: true,
        disabled: userStore.userInfo.orgId != 484,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      },
      {
        // label: '性别',
        span: 3,
        prop: 'deviceType',
        placeholder: '设备类型',
        type: 'tree',
        multiple: false,
        // checkStrictly: false,
        // filterable: true,//模糊搜索
        dicData: terminalDeviceTree
      },
      {
        // label: '性别',
        span: 3,
        prop: 'status',
        placeholder: '启用状态',
        type: 'select',
        multiple: false,
        // filterable: true,//模糊搜索
        dicData: enable_status
      },
      {
        // label: '性别',
        span: 5,
        prop: 'warrantyDateArr',
        placeholder: '保修期时间',
        type: 'input'
      },
      {
        prop: 'purchaseDateArr',
        type: 'daterange',
        span: 5,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '购买开始时间',
        endPlaceholder: '购买结束时间'
      },
      {
        prop: 'createTimeArr',
        type: 'daterange',
        span: 5,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '录入开始时间',
        endPlaceholder: '录入结束时间'
      },
      {
        // label: '性别',
        span: 3,
        prop: 'isRenewal',
        placeholder: '是否已续费',
        type: 'select',
        multiple: false,
        // filterable: true,//模糊搜索
        dicData: yes_or_no
      }
    ]
  },
  showSearch: true,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  disTransfer: true /* 转入知识库是否可编辑 */,
  loading: false,
  tableList: [],
  dialogParam: {}
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  showSearch,
  disUpdate,
  disDelete,
  disTransfer,
  loading,
  tableList,
  dialogParam
} = toRefs(data)
watch(
  [() => route.query.salesOrderData],
  async () => {
    if (route.query.salesOrderData) {
      queryParams.value = JSON.parse(route.query.salesOrderData)
      getList()
    }
  },
  {
    immediate: true
  }
)

const tableCol = ref(INITTABLE)
// 自定义列表弹窗参数
const diaTable = ref({
  open: false,
  // tableName:'',
  tableCol: []
})

// 自定义列表
const handleTable = () => {
  diaTable.value = {
    open: true,
    tableName: 'terminalTable',
    tableCol: tableCol.value,
    initCol: INITTABLE
  }
}

// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}

// 初始化
async function init() {
  // 初始化列表配置
  tableCol.value = initTable('terminalTable', INITTABLE)

  // 获取税务机关下拉数据
  commonStore.getTaxTreeData().then(data => {
    taxTreeData.value = data
  })
  getList()
}

// 重置
function handleEmpty(formEl) {
  queryParams.value.warrantyStartDate = ''
  queryParams.value.warrantyEndDate = ''
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}

// 获取数据列表
function getList() {
  loading.value = true
  console.log('queryParams.value2==>', queryParams.value)
  listTerminal(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
  })
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
  let transfer = selection.some(item => item.isTransfer == '是')
  disTransfer.value = !selection.length || transfer
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}

// 删除
function handleDelete(row) {
  let rowIds = row.id || ids.value
  // console.log('selectArr-->', selectArr.value, 'id==>', rowIds)
  proxy.$modal
    .confirm('是否删除该终端数据')
    .then(function () {
      return delTerminal(rowIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

// 跟进
const accessParam = ref({})
function handleAccess(row) {
  /***订单模块 */
  console.log('row==>', row)
  accessParam.value.isVisible = true
  accessParam.value.businessId = row.id
  accessParam.value.customerName = row.customerName
}
// 跟进记录弹窗
const AccessDia = ref({
  title: '跟进记录',
  open: false,
  width: '1000px',
  tableParam: {}
})
const handleAccessDia = row => {
  AccessDia.value.open = true
  AccessDia.value.tableParam = {
    businessId: row.id, //业务id
    customerName: row.customerName
  }
}
// 关闭导入弹窗
function closeAccessDia() {
  AccessDia.value.open = false
}

// 表单弹窗
const formDialog = ref({
  title: '终端信息',
  open: false
})
const formData = ref({})
const formRules = ref({
  deviceType: [
    {
      required: true,
      message: '请选择设备型号',
      trigger: ['blur', 'change']
    }
  ],
  city: [
    {
      required: true,
      message: '请选择市局',
      trigger: ['blur', 'change']
    }
  ],
  district: [
    {
      required: true,
      message: '请选择区局',
      trigger: ['blur', 'change']
    }
  ],
  customerName: [
    {
      required: true,
      message: '请输入单位名称',
      trigger: ['blur', 'change']
    }
  ],
  networkType: [
    {
      required: true,
      message: '请选择网点类型',
      trigger: ['blur', 'change']
    }
  ],
  serialNumber: [
    {
      required: true,
      message: '请输入序列号',
      trigger: ['blur', 'change']
    }
  ],
  operations: [
    {
      required: true,
      message: '请输入运维人员',
      trigger: ['blur', 'change']
    }
  ],
  contact: [
    {
      required: true,
      message: '请输入联系人',
      trigger: ['blur', 'change']
    }
  ],
  telephone: [
    {
      required: true,
      message: '请输入电话',
      trigger: ['blur', 'change']
    }
  ],
  address: [
    {
      required: true,
      message: '请输入地址',
      trigger: ['blur', 'change']
    }
  ],
  status: [
    {
      required: true,
      message: '请选择状态',
      trigger: ['blur', 'change']
    }
  ],
  purchaseDate: [
    {
      required: true,
      message: '请选择购买时间',
      trigger: ['blur', 'change']
    }
  ],
  warrantyDate: [
    {
      required: true,
      message: '请选择保修期',
      trigger: ['blur', 'change']
    }
  ],
  isWarranty: [
    {
      required: true,
      message: '请选择是否延保',
      trigger: ['blur', 'change']
    }
  ]
})

// 编辑按钮
const handleUpdate = row => {
  let rowIds = row.id || ids.value
  getTerminal(rowIds).then(res => {
    formData.value = res.data
    formDialog.value.open = true
    taxDistrictBureau.value =
      taxTreeData.value[0].children.find(item => item.id == formData.value.city)
        ?.children || []
  })
}

// 续费按钮
const handleRenew = row => {
  let rowIds = row.id || ids.value
  proxy.$modal
    .confirm('是否续费选中终端')
    .then(function () {
      renewTerminal({ ids: ids.value }).then(res => {
        proxy.$modal.msgSuccess('续费成功！')
        getList()
      })
    })
    .catch(() => {})
}

// 打开表单
function handleOpen() {
  formData.value = {}
  proxy.resetForm('formRef')
  formDialog.value.open = true
}
// 市局改变时
const changeTax = val => {
  let salesData = taxTreeData.value[0].children.find(item => item.id == val)
  // formData.value.cityName = salesData?.label || ''
  taxDistrictBureau.value = salesData?.children || []
  formData.value.district = ''
}
// 保存表单
function handleSubmit() {
  proxy.$refs.formRef.validate((valid, msg) => {
    if (valid) {
      saveTerminal(formData.value).then(res => {
        proxy.$modal.msgSuccess('保存成功！')
        formDialog.value.open = false
        getList()
      })
    }
  })
}

/*** +++++++++++++++++++++++++   关联订单   +++++++++++++++++++++++++***/
const orderParams = ref({})
// 打开弹窗
function activeOrdDialog() {
  orderParams.value = {
    visible: true, // 显示dialog
    multiple: false, // 是否多选
    otherParameters: {
      property: '0'
    }
    // defaultSelect: formData.value.oppositeId ? formData.value.oppositeId : [] // 默认选择数据
  }
}

async function ordRelatedOver(val) {
  console.log(val, 'order')
  if (val) {
    formData.value.customerName = val.customerName
    formData.value.contact = val.cusLinkName
    formData.value.telephone = val.linkPhone
    // formData.value.address = val.
    formData.value.purchaseDate = val.receiptsDate
  }
  ordCloseDialog()
}
// 关闭弹窗
function ordCloseDialog() {
  orderParams.value.visible = false
}
/*** +++++++++++++++++++++++++   关联订单结束   +++++++++++++++++++++++++***/

/* 统计弹窗开始 */
const statisticsDia = ref({
  title: '统计',
  open: false,
  width: '1000px'
})
const queryParamsStatistics = ref({})
const loadingStatistics = ref(false)
const dataListStatistics = ref([])
// 统计
const handleStatistics = () => {
  queryParamsStatistics.value = {}
  statisticsDia.value.open = true
  getListStatistics()
}
const getListStatistics = () => {
  loadingStatistics.value = true
  statisticsTerminal(queryParamsStatistics.value).then(res => {
    dataListStatistics.value = res.data
    loadingStatistics.value = false
  })
}
const closeStatisticsDia = () => {
  statisticsDia.value.open = false
}
const handleDbClick = row => {
  // console.log('handleDbClick==>', row)
}
/* 统计弹窗结束 */

/* 上传合同开始 */
const diaParam = ref({})
//打开上传合同弹窗
function uploadContract(row) {
  /***订单模块 */
  diaParam.value.open = true
  diaParam.value.multiple = true // 是否多选
  diaParam.value.title = row.customerName // 是否多选
  diaParam.value.queryParams = {
    partya: row.customerId, // 根据客户id查询合同列表
    uploadType: '1'
  }
  diaParam.value.initData = {
    ...row
  }
}

// 确认关联合同
function saveFn(data) {
  console.log('data=>', data)
  let param = {
    contractList: data.selectData.filter(e => e.rcId),
    orderId: data.formData.id
  }
  supervisionContract(param).then(res => {
    getList()
  })
}

/* 上传合同结束 */

/* 数据导入 开始 */
// 导入弹窗
const uploadDia = ref({
  title: '导入终端',
  open: false,
  message: ''
})
const uploadType = {
  type01: ['.xls', '.xlsx'],
  type02: [
    '.rar',
    '.zip',
    '.doc',
    '.docx',
    '.pdf',
    '.xls',
    '.xlsx',
    '.ppt',
    '.pptx',
    '.gif',
    '.jpg',
    '.jpeg',
    '.png'
  ]
}
// 模板下载
const downUrl = async function downUrl() {
  exportModel()
}
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
const uploadLoading = ref(false)
function beforeAvatarUpload(rawFile, type) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = uploadType[type].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      `上传文件只能是${uploadType[type]
        .toString()
        .replace(/\./g, '')
        .replace(/,/g, '、')}格式!`
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params, type) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  try {
    let res = await importTerminal(uploadData)
    uploadLoading.value = false
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      uploadDia.value.message = res.msg
      getList()
    }
  } catch (error) {
    uploadLoading.value = false
  }
}

// 导出明细
const exportDetail = () => {
  downLoadByUrl('/ord/terminal/device/export', queryParams.value, {
    fileName: `终端${proxy.parseTime(new Date())}.xlsx`,
    onDownload: e => {
      console.log('e==>', e)
    }
  })
  // proxy.downLoadByUrl(
  //   '/ord/terminal/device/export',
  //   queryParams.value,
  //   '终端.xlsx'
  // )
}
// 导出模板
const exportModel = () => {
  proxy.downLoadByUrl(
    '/ord/terminal/device/export/template',
    queryParams.value,
    '终端模板.xlsx'
  )
}

// 关闭导入弹窗
function closeUpload() {
  uploadDia.value.open = false
  uploadDia.value.message = ''
}
/* 数据导入 结束 */

init()
</script>
<style scoped lang="scss">
@import '@/assets/styles/myStyle.scss';
</style>
<style scoped lang="scss">
.search-drawer-retract {
  color: #999999;
}
</style>
